package ru.ipo.problemsapi;


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 01.04.11
 * Time: 3:00
 */
public class MapProblem implements Problem {

    private boolean teacher = false;

    private final Map<String, String> strings;
    private final Map<String, byte[]> bytes;

    public MapProblem(Map<String, String> strings) {
        if (strings == null)
            throw new NullPointerException();
        this.strings = strings;
        this.bytes = new HashMap<String, byte[]>();
    }

    public MapProblem(Map<String, String> strings, Map<String, byte[]> bytes) {
        if (strings == null)
            throw new NullPointerException();
        if (bytes == null)
            throw new NullPointerException();

        for (String key : strings.keySet())
            if (bytes.containsKey(key))
                throw new IllegalArgumentException("Key " + key + " is in both maps");

        this.strings = strings;
        this.bytes = bytes;
    }

    public InputStream getReadStream(String name) {
        byte[] res = bytes.get(name);
        if (res != null)
            return new ByteArrayInputStream(res);
        String s = strings.get(name);
        if (s != null)
            return new ByteArrayInputStream(s.getBytes(new ExtendedProblem(this).getEncoding(name)));
        return null;
    }

    public String getString(String name) {
        String s = strings.get(name);
        if (s == null)
            if (bytes.get(name) != null)
                return new String(bytes.get(name), new ExtendedProblem(this).getEncoding(name));
        return s;
    }

    public boolean isTeacher(String name) {
        return teacher;
    }

    public void setTeacher(boolean teacher) {
        this.teacher = teacher;
    }

    public List<String> listNames() {
        List<String> res = new ArrayList<String>(strings.keySet());
        res.addAll(bytes.keySet());
        return res;
    }
}
